package net.alcuria.ball;

import java.util.List;

import javax.microedition.khronos.opengles.GL10;

import net.alcuria.framework.Game;
import net.alcuria.framework.Input.TouchEvent;
import net.alcuria.framework.gl.Animation;
import net.alcuria.framework.gl.Camera2D;
import net.alcuria.framework.gl.SpriteBatcher;
import net.alcuria.framework.gl.TextureRegion;
import net.alcuria.framework.impl.GLScreen;
import net.alcuria.framework.math.OverlapTester;
import net.alcuria.framework.math.Rectangle;
import net.alcuria.framework.math.Vector2;

public class GLMainMenuScreen extends GLScreen {
	Camera2D guiCam;
	SpriteBatcher batcher;
	Rectangle soundBounds;
	Rectangle playBounds;
	Vector2 touchPoint;
	
	float stateTime = 0.0f;

	public GLMainMenuScreen(Game game) {
		super(game);
		guiCam = new Camera2D(glGraphics, 544, 320);
		batcher = new SpriteBatcher(glGraphics, 100);
		soundBounds = new Rectangle(0, 0, 64, 64);
		playBounds = new Rectangle(350 - 128, 250 - 128, 256, 128);
		touchPoint = new Vector2();
	}

	@Override
	public void update(float deltaTime) {
		List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
		int len = touchEvents.size();
		for (int i=0; i < len; i++) {
			TouchEvent event = touchEvents.get(i);
			if(event.type == TouchEvent.TOUCH_UP) {
				touchPoint.set(event.x, event.y);
				guiCam.touchToWorld(touchPoint);
				if(OverlapTester.pointInRectangle(playBounds, touchPoint)) {
					Assets.click.play(1.0f);
					Assets.glItems.dispose();
					Assets.glBackground.dispose();
					game.setScreen(new MapViewerScreen(game));
					return;
				}
				if(OverlapTester.pointInRectangle(soundBounds, touchPoint)) {
					Assets.click.play(1.0f);
					Settings.soundEnabled = !Settings.soundEnabled;
					if(Settings.soundEnabled)
						Assets.elysium.play();
					else
						Assets.elysium.stop();
				}
			}
		}

	}

	@Override
	public void present(float deltaTime) {
		GL10 gl = glGraphics.getGL();
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		guiCam.setViewportAndMatrices();

		gl.glEnable(GL10.GL_TEXTURE_2D);
		batcher.beginBatch(Assets.glBackground);
		batcher.drawSprite(272, 160, 544, 320, Assets.glBackgroundRegion);
		batcher.endBatch();

		gl.glEnable(GL10.GL_BLEND);
		gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
			
		batcher.beginBatch(Assets.glItems);
		batcher.drawSprite(350, 250, 300, 110, Assets.mainMenu.getKeyFrame(stateTime, Animation.ANIMATION_LOOPING));
		batcher.drawSprite(32, 32, 64, 64, Settings.soundEnabled?Assets.soundOn:Assets.soundOff);
		batcher.endBatch();
		
		gl.glDisable(GL10.GL_BLEND);
		
		stateTime += deltaTime;
	}

	@Override
	public void pause() {
		Settings.save(game.getFileIO());
	}
	@Override
	public void resume() {
	}
	@Override
	public void dispose() {
	}

}
